package com.qiyue.admin.config.interceptor;

import com.qiyue.admin.auth.configuration.UserAuthConfig;
import com.qiyue.admin.auth.utils.jwt.utils.UserAuthUtil;
import com.qiyue.admin.auth.utils.model.IJWTInfo;
import com.qiyue.common.context.BaseContextHandler;
import com.qiyue.common.utils.IpUtils;
import com.qiyue.utils.ip.IPUtil;
import com.qiyue.utils.string.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *  ybh
 *  用户认证拦截器
 *
 *  主要处理以下问题
 *   1、对url方法进行拦截
 *   2、将用户token 解密并存入本地线程
 *
 */
@Slf4j
public class UserAuthRestIntercptor extends HandlerInterceptorAdapter {


    @Autowired
    private UserAuthUtil userAuthUtil;

    @Autowired
    private UserAuthConfig userAuthConfig;

    /**
     *  预处理
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HandlerMethod handlerMethod = (HandlerMethod) handler;

        /**
         * 根据注解放行 ，待实现
         */

        String token = request.getHeader(userAuthConfig.getTokenHeader());
        //判断是否有携带token
        if (StringUtils.isEmpty(token)){
        //如果没有,尝试从你的小饼干中获取
            if(request.getCookies() != null){
                for( Cookie cookie : request.getCookies()){
                    if (cookie.getName().equals(userAuthConfig.getTokenHeader())){
                        token = cookie.getName();
                    }
                }
            }
            return super.preHandle(request, response, handler);
        }
        //存入线程

        IJWTInfo ijwtInfo = userAuthUtil.getInfoFromToken(token);
        BaseContextHandler.setName(ijwtInfo.getName());
        BaseContextHandler.setUserID(ijwtInfo.getId());
        BaseContextHandler.setUserAccount(ijwtInfo.getAccount());
        BaseContextHandler.setUserHost(IpUtils.getIpAddr(request));
        return super.preHandle(request, response, handler);
    }
}
